import { ResultEnum } from '@/enums/httpEnum'; //配置
import { pinia, toastStore, userStore } from '@/stores';
import type { FormField, HttpConfig, HttpResponseData } from '@/types/http';
import { getBaseUrl, getEnvValue } from '@/utils/env';
import { page } from '@/utils/index'; //获取页面站
import { difference, isEmpty } from 'lodash';
import Request, { type HttpResponse } from 'luch-request';
//import { encrypt, getCSRFToken } from './AES';


const toast = toastStore(pinia);
const store = userStore(pinia);


//获取请求前环境配置信息
//const APPID = getEnvValue('VITE_APPID');
//const APPKEY = getEnvValue('VITE_APPKEY');
//const publicKey = getEnvValue('VITE_PUBLICKEY');

const HEADER = {
	//'Content-Type': 'application/json;charset=UTF-8;',
	Accept: 'application/json, text/plain, */*',
	//'X-Auth-AppID': APPID,
	//'X-Source': 'miniapp',
  'Authorization':store.token ? store.token : uni.getStorageSync('token')
	//'X-Auth-Token':store.token ? store.token : '',
};
//建立请求配置
function createRequest() {
	return new Request({
		baseURL: getEnvValue('VITE_BASE_URL'),
		//header: HEADER,
		timeout: 1000 * 60,
		validateStatus: function (status) {
			return status >= 200 && status <= 400;
		},
	});
}


const http = createRequest();
/**
 * 请求拦截器
 */
http.interceptors.request.use(
	async (config) => {
		/*if (config.custom?.apiLevel === 'api') {
			setApiHeader(config);
		}*/
		config.header = {
		  ...config.header,
		  'Authorization':store.token ? store.token : uni.getStorageSync('token')
		}
		return config;
	},
	(options) => {
		console.log(options);
		return Promise.reject(options)
  	}
);

/**
 * 响应拦截器
 */
http.interceptors.response.use(
  (response: HttpResponse<HttpResponseData>) => {
		const {data} = response;
		//const { data: resData } = response;
		//const { status, result } = resData;
		//错误处理
		if(data.code == 'ERROR'){
		  toast.setData({
			title:data.message?.message,
			type: 'warning',
		  })
		  return Promise.resolve({
			code:'ERROR',
			data:data.message?.message
		  });
		}

	   /* if(data.code == '401' || data.code =='403'){
		  uni.reLaunch({
			url: `/pages/login/index?loginSuccessRedirectUrl=${page()}`,
		  });
		}*/
		return data;
	},
	(response) => {
    console.log(response)
		return Promise.reject(response);
	}
);



/**
 *
 * @param url
 * @param params
 * @param {HttpConfig} config
 * @returns {Promise<HttpResponseData>} Promise
 */
const get = (url: string, params: any, config: HttpConfig = {}): Promise<HttpResponseData> => {
	const { header, ...arg } = config
	return http
		.get(url, { params, header })
		.then((res): Promise<HttpResponseData> => {
			/*let err = {};
			if (res.data.result && res.data.status === ResultEnum.ERROR) {
				err = handleErrorCode(res.data.result, config.formField || [], config);
			}
			if (!isEmpty(err)) {
				return Promise.resolve({ status: res.data.status, result: err });
			} else {
				return Promise.resolve(res.data);
			}*/
		  return res;
		})

};

/**
 * @description: post请求
 * @param url : string
 * @param data : any
 * @param {HttpConfig} config
 * @returns
 */
const post = (
	url: string,
	data: any,
	config: HttpConfig = { }
) => {
	//const _data = config.isCsrf ? encrypt(data) : data;

	const { header, ...arg } = config;
	return http.post(url, data, { header }).then((res) => {
		/*let err = {};
		if (res.data.result && res.data.status === ResultEnum.ERROR) {
			err = handleErrorCode(res.data.result, config.formField || [], config);
		}
		if (!isEmpty(err)) {
			return Promise.resolve({ status: res.data.status, result: err });
		} else {
			return Promise.resolve(res.data);
		}*/
    return res;
	});
};


/**
 * @description: post请求
 * @param url : string
 * @param data : any
 * @param {HttpConfig} config
 * @returns
 */
const postFile = (
	url: string,
	data: any,
	config: HttpConfig = { apiLevel: 'user' }
) => {
	//const _data = config.isCsrf ? encrypt(data) : data;

	const { header, ...arg } = config;
	return http.post(url, data, {
    header,
    custom: arg,
    responseType: 'arraybuffer',
  }).then((res) => {
		/*let err = {};
		if (res.data.result && res.data.status === ResultEnum.ERROR) {
			err = handleErrorCode(res.data.result, config.formField || [], config);
		}
		if (!isEmpty(err)) {
			return Promise.resolve({ status: res.data.status, result: err });
		} else {
			return Promise.resolve(res.data);
		}*/
    return res;
	});
};



/*const getApiToken = () => {

	return new Promise((resolve, reject) => {
		let csrfToken = '';
		try {
			csrfToken = store.csrfToken || [];
		} catch (error) {}
		post(
			'/sdk/auth/connect',
			{ publicKey: publicKey },
			{
				header: {
					'X-Auth-AppID': APPID,
					'X-Auth-AppKey': APPKEY,
					'X-Auth-CSRF': csrfToken,
				},
				apiLevel: 'api',
			}
		)
			.then((res) => {
				store.setApiToken(res.result);
				return resolve(res);
			})
			.catch((err) => {
				return reject(err);
			});
	});
};*/



export { http, get, post, postFile };
